from os.path import dirname, join
from pgtools.plugins.db.DBManager import DBManager, DBResult


class BaseEntity:
    """
    实体类基类，提供所有实体类共有的基础方法，使用sqlite3数据库存储数据
    """
    db = DBManager()

    def __init__(self, table_name: str):
        self.table_name = table_name
        self.dbfile = join(dirname(__file__), 'db.sqlite3')
        self.db.connect(self.dbfile)

    def add_one(self, **kwargs):
        self.db.insert(self.table_name, **kwargs)

    def delete(self, condition):
        self.db.delete(self.table_name, condition)

    def set(self, condition, **kwargs):
        self.db.update(self.table_name, condition, **kwargs)

    def get(self, condition) -> DBResult:
        return self.db.select(self.table_name,
                              condition=condition)

    def get_all(self) -> list:
        r = self.db.select(self.table_name)
        return r.as_dict() if r else []

    def count(self, condition):
        return self.db.count(self.table_name, condition=condition)

    @classmethod
    def close(cls):
        cls.db.close()
